<template>
  <div v-if="loading">正在加载...</div>
  <el-select
    v-else
    :value="value"
    :college-id="collegeId"
    :show-major-name="showMajorName"
    placeholder="请选择专业"
    @change="$emit('input', $event)"
  >
    <el-option
      v-for="major in majorList"
      :key="major.id"
      :label="major.majorName"
      :value="major.id"
    />
  </el-select>
</template>

<script>
import { getMajorList } from '@/api/admin/major'

export default {
  name: 'MajorSelect',
  props: {
    value: {
      type: Number,
      default: undefined
    },
    collegeId: {
      type: Number,
      default: undefined
    },
    showMajorName: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      majorList: []
    }
  },
  watch: {
    collegeId(val, oldVal) {
      // 重置id时不需要发送请求
      if (val === undefined) {
        return
      }
      // id变化时清空当前值并重新发送请求
      if (val !== oldVal) {
        this.$emit('input', undefined)
        this.getMajorList()
      }
    }
  },
  created() {
    this.showMajorName ? this.getMajorList() : this.loading = false
  },
  methods: {
    /**
     * 获取专业信息
     */
    async getMajorList() {
      this.majorList = await getMajorList(this.collegeId)
      this.loading = false
    }
  }
}
</script>
